import 'package:bot_toast/bot_toast.dart';
import 'package:self32/entity/inventory_entity.dart';
import '../event/inventory_event.dart';
import '../event/set_eas_event.dart';
import '../event/user_id_event.dart';
import '../main.dart';
import '../util/convert_util.dart';
import '../util/toast_util.dart';
import 'socket_manager.dart';

class ResultHandler{

  SocketManager manager = SocketManager();

  handler(data){
    var cmd = data['cmd'];
    var status = data['status'];
    print('cmd = $cmd, status = $status');

    // if(cmd == 'locker_check' && status == 200){
    //   eventFactory.fire(CheckResultEvent('locker_check', data['data']['check']));
    // }
    // if(cmd == 'rfid_uhf_check' && status == 200){
    //   eventFactory.fire(CheckResultEvent('rfid_uhf_check', data['data']['check']));
    // }
    if(cmd == 'rfid_hf_check' && status != 200){
      toastError('读写器异常');
    }
    if(cmd == 'card_reader_m1_inventory' ){
      if(status == 200){
        String? uid =data['data']['uid'];
        if(uid != null && uid.length == 8){
          String exUid = uid.substring(6,8)+uid.substring(4,6)+uid.substring(2,4)+uid.substring(0,2);
          String uidNo = hexToInt(exUid).toString();
          while(uidNo.length<10){
            uidNo = '0$uidNo';
          }
          eventFactory.fire(UserIdEvent(uidNo,null));
        }else{
          eventFactory.fire(UserIdEvent(uid??'null',null));
        }
      }else{
        manager.start();
        // eventFactory.fire(UserIdEvent('null'));
      }
    }
    if(cmd == 'card_reader_icr_inventory' ){
      if(status == 200){
        eventFactory.fire(UserIdEvent(data['data']['uid'],null));
      }else{
        manager.start();
        // eventFactory.fire(UserIdEvent('null'));
      }
    }

    if(cmd == 'rfid_hf_eas' ){
      if(status == 200){
        manager.afi(data['data']['uid'],data['data']['no']);
      }else{
        manager.fail(data['data']['uid'],data['data']['no']);
      }
    }

    if(cmd == 'rfid_hf_afi' ){
      if(status == 200){
        manager.success(data['data']['uid'],data['data']['no']);
      }else{
        manager.fail(data['data']['uid'],data['data']['no']);
      }
    }
    if(cmd == 'rfid_hf_scan' && status == 200){
      manager.start();
      List<dynamic> str = data['data']['list'];
      List<InventoryEntity> listData = [];
      for (var element in str) {
        listData.add(InventoryEntity.fromJson(element));
      }
      eventFactory.fire(InventoryEvent(listData));
    }
    // if(cmd == 'rfid_uhf_scan' && status == 200){
    //   eventFactory.fire(InventoryRfidEvent(InventoryEntity.fromJson(data['data'])));
    // }

    if((cmd == 'rfid_hf_scan' ||cmd == 'rfid_uhf_scan' ) && status == 400){
      manager.start();
      BotToast.closeAllLoading();
      // toastWarn(data['error']);
    }

  }

}